package com.yourenbang.lingyun.transaction.web.service.impl.pay.transaction;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.pay.PayRateEnum;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.constants.enums.table.PayTransactionEnum;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.core.util.date.LocalDateUtils;
import com.yourenbang.lingyun.domain.Terminal21;
import com.yourenbang.lingyun.transaction.constant.LklTransTypeEnum;
import com.yourenbang.lingyun.transaction.web.domain.dto.yxy.LdysTradeDTO;
import com.yourenbang.lingyun.transaction.web.service.PayTransactionFormatService;
import com.yourenbang.terminal.api.service.RpcYxyTerminalService;
import com.yourenbang.transaction.api.model.vo.pay.PayTransaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 联动优势交易格式化
 * @Date 20220808
 * @Created by Jason
 */
@Service
@Slf4j
public class LdysPayTransactionFormatServiceImpl implements PayTransactionFormatService {
    @Autowired
    private RpcYxyTerminalService rpcYxyTerminalService;

    @Override
    public PayTransaction payTransactionFormat(JSONObject jsonObject) {
        KLog.info("ldys格式化交易推送入参:{}", jsonObject.toJSONString());
        LdysTradeDTO ldysTradeDTO = jsonObject.toJavaObject(LdysTradeDTO.class);

        PayTransaction payTransaction = new PayTransaction();

        payTransaction.setMerchantNo(ldysTradeDTO.getMerNo());
        payTransaction.setMerchantName(ldysTradeDTO.getMerName());

        payTransaction.setOrderNo(ldysTradeDTO.getSerial());
        payTransaction.setTransactionNo(ldysTradeDTO.getSerial());
        payTransaction.setSysRef(ldysTradeDTO.getSerial());

        payTransaction.setTransactionAmount(new BigDecimal(ldysTradeDTO.getAmount()).divide(new BigDecimal("100")));

        if (StringUtils.isBlank(ldysTradeDTO.getTradeCharges())) {
            payTransaction.setTransactionFee(BigDecimal.ZERO);
        }else {
            payTransaction.setTransactionFee(new BigDecimal(ldysTradeDTO.getTradeCharges()).divide(new BigDecimal("100")));
        }

        payTransaction.setCardFlag(formatCardFlagLdys(ldysTradeDTO.getCardType(), ldysTradeDTO.getPayType()));
        try {
            if (StringUtils.equalsAny(payTransaction.getCardFlag(), PayTransactionEnum.CardFlagEnum.ALIPAY.getCode(),
                    PayTransactionEnum.CardFlagEnum.WECHAT.getCode())) {
                payTransaction.setRate(PayRateEnum.f38_qr.getShotCode());
            } else {
                payTransaction.setRate(payTransaction.getTransactionFee().divide(payTransaction.getTransactionAmount(),
                        4, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("10000")).intValue());
            }
        } catch (Exception e) {
            log.warn("ldys计算费率失败:{}", ldysTradeDTO.toJSON());
        }
        payTransaction.setTerminalId(ldysTradeDTO.getTerNo());
//        payTransaction.setPsamNo("");
        payTransaction.setSn(ldysTradeDTO.getSn());
        payTransaction.setTransactionCardNo(ldysTradeDTO.getPan());
//        payTransaction.setTransactionBank("");
        payTransaction.setTransactionCardType(formatCardFlagLdys(ldysTradeDTO.getCardType(), ldysTradeDTO.getPayType()));
//        payTransaction.setSettlementCardNo("");
//        payTransaction.setSettlementBank("");
//        payTransaction.setSettlementCardType("");
        payTransaction.setStatus(formatTradeStatusLdys(ldysTradeDTO.getStatus()));
        LocalDateTime transTime = LocalDateTime.now();
        if (StringUtils.isNotBlank(ldysTradeDTO.getLocalDate()) && StringUtils.isNotBlank(ldysTradeDTO.getLocalTime())) {
            transTime = LocalDateUtils.stringToLocalDateTime
                    (ldysTradeDTO.getLocalDate() + " " + ldysTradeDTO.getLocalTime(), DateFormat.DATETIME_DEFAULT.getPartten());
        }

        payTransaction.setTransactionTime(transTime);
        payTransaction.setTransactionMonth(
                LocalDateUtils.localDateTimeByFormat(transTime, DateFormat.DATE_MONTH.getPartten()));
        payTransaction.setTransactionDay(LocalDateUtils.localDateTimeByFormat(transTime, DateFormat.DATE_COMPACT.getPartten()));

//        payTransaction.setFrontSuccessTime(LocalDateTime.now());
//        payTransaction.setProvinceCode("");
//        payTransaction.setCityCode("");
//        payTransaction.setDistrictCode("");
//        payTransaction.setLongitude("");
//        payTransaction.setLatitude("");
//        payTransaction.setAreaCode("");

//        payTransaction.setWithdrawalOrderNo("");
//        payTransaction.setWithdrawalTransactionNo("");
//        payTransaction.setWithdrawalAmount(new BigDecimal("0"));
//        payTransaction.setWithdrawalFee(new BigDecimal("0"));
        //ldys附加手续费
        if (StringUtils.isBlank(ldysTradeDTO.getTradeChargesFj())) {
            payTransaction.setFeeAmt(BigDecimal.ZERO);
        }else {
            payTransaction.setFeeAmt(new BigDecimal(ldysTradeDTO.getTradeChargesFj()).divide(new BigDecimal("100")));
        }

        BigDecimal noSettleAmt = BigDecimal.ZERO;
        if (StringUtils.isNotBlank(ldysTradeDTO.getNoSettleAmt())) {
            noSettleAmt = new BigDecimal(ldysTradeDTO.getNoSettleAmt());
        }

        payTransaction.setAccAmt(payTransaction.getTransactionAmount().subtract(payTransaction.getTransactionFee())
        .subtract(payTransaction.getFeeAmt()).subtract(noSettleAmt));
//        payTransaction.setWithdrawalQueryTime(LocalDateTime.now());
//        payTransaction.setWithdrawalQueryCount(0);
//        payTransaction.setWithdrawalDrawTime(LocalDateTime.now());
//        payTransaction.setWithdrawalDrawCount(0);
        payTransaction.setWithdrawalStatus(PayTransactionEnum.WithdrawalStatusEnum.STATUS_40.getCode());

        Terminal21 terminal21= rpcYxyTerminalService.getTerminalBySn(payTransaction.getSn());
        if(Objects.isNull(terminal21)){
            return null;
        }
        payTransaction.setChannelId(terminal21.getChannelId());
        payTransaction.setPlatNo(PlatNoEnums.YXY.getCode());
        payTransaction.setIsDel(false);

        payTransaction.setTransType(formatPledgeStatusLdys(ldysTradeDTO.getMsgType()));

        //分润标识
        payTransaction.setProfitFlag(checkIsProfitFlagLdys(payTransaction));

        return payTransaction;
    }

    @Override
    public JSONObject dyUrlRequest(String uri, Map<String, Object> bodyJson) {
        return null;
    }

    @Override
    public JSONObject dyUrlRequestByPayType(String uri, Map<String, Object> bodyJson, PayTypeEnum payTypeEnum) {
        return null;
    }

    /**
     * ldys判断交易状态
     *
     * @param respCode
     * @return
     */
    private Short formatTradeStatusLdys(String respCode) {
        if (StringUtils.equalsAny(respCode, "0", "1")) {
            return PayTransactionEnum.TransactionStatus.STATUS_10.getCode();
        }
        return PayTransactionEnum.TransactionStatus.STATUS_20.getCode();
    }

    /**
     * ldys判断押金状态
     * H007消费、Y007押金消费、S007流量卡交易
     * @param msgType
     * @return
     */
    private String formatPledgeStatusLdys(String msgType) {
        if (StringUtils.equalsAny(msgType, "Y007")) {
            return LklTransTypeEnum.TYPE_412001.getTransType();
        }
        if (StringUtils.equalsAny(msgType, "S007")) {
            return LklTransTypeEnum.TYPE_012003.getTransType();
        }
        return LklTransTypeEnum.TYPE_012001.getTransType();
    }

    /**
     * 联动优势判断交易卡类型
     *
     * @param cardType 0：未知、1：借记卡、2：贷记卡、3：预付费卡
     * @param payType  0-银行卡收单 1-银联二维码 2-微信 3-支付宝
     * @return
     */
    private String formatCardFlagLdys(String cardType, String payType) {

        if (StringUtils.equals(payType, "2")) {
            return PayTransactionEnum.CardFlagEnum.WECHAT.getCode();
        }
        if (StringUtils.equals(payType, "3")) {
            return PayTransactionEnum.CardFlagEnum.ALIPAY.getCode();
        }
        if (StringUtils.equals(payType, "1")) {
            return PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode();
        }
        if (StringUtils.equals(cardType, "1")) {
            return PayTransactionEnum.CardFlagEnum.BORROW_CARD.getCode();
        }
        if (StringUtils.equalsIgnoreCase(cardType, "2")) {
            return PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode();
        }
        return cardType + "_" + payType;

    }

    //判断是否计入分润
    private boolean checkIsProfitFlagLdys(PayTransaction payTransaction) {

        //贷记卡且非押金交易,非流量卡交易才计入分润
        if (StringUtils.equalsAny(payTransaction.getCardFlag(), PayTransactionEnum.CardFlagEnum.ALIPAY.getCode(),
                PayTransactionEnum.CardFlagEnum.WECHAT.getCode(),
                PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode(),
                PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode()) &&
                !StringUtils.equals(LklTransTypeEnum.TYPE_412001.getTransType(), payTransaction.getTransType())) {
            return true;
        }

        return false;
    }
}
